<template>
  <div class="monitor-integration">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="left">
        <h2>系统集成管理</h2>
        <el-tag type="info" class="ml-2">共 {{ total }} 个集成系统</el-tag>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增集成
        </el-button>
        <el-button type="success" @click="handleSync">
          <el-icon><Refresh /></el-icon>同步数据
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>导出配置
        </el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="系统类型">
        <el-select v-model="queryParams.type" placeholder="请选择系统类型" clearable>
          <el-option
            v-for="item in systemTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="系统状态">
        <el-select v-model="queryParams.status" placeholder="请选择系统状态" clearable>
          <el-option
            v-for="item in systemStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="系统名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入系统名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 系统列表 -->
    <el-table
      v-loading="loading"
      :data="systemList"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="系统名称" prop="name" min-width="150" show-overflow-tooltip />
      <el-table-column label="系统类型" prop="type" width="120">
        <template #default="{ row }">
          <el-tag :type="getSystemTypeTag(row.type)">{{ getSystemTypeLabel(row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="接口地址" prop="apiUrl" min-width="200" show-overflow-tooltip />
      <el-table-column label="认证方式" prop="authType" width="120">
        <template #default="{ row }">
          {{ getAuthTypeLabel(row.authType) }}
        </template>
      </el-table-column>
      <el-table-column label="同步状态" prop="syncStatus" width="100">
        <template #default="{ row }">
          <el-tag :type="getSyncStatusTag(row.syncStatus)">
            {{ getSyncStatusLabel(row.syncStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="最后同步时间" prop="lastSyncTime" width="180" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button type="success" link @click="handleTest(row)">
            <el-icon><VideoPlay /></el-icon>测试
          </el-button>
          <el-button type="warning" link @click="handleMonitor(row)">
            <el-icon><Monitor /></el-icon>监控
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 系统配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增集成' : '编辑集成'"
      width="800px"
      append-to-body
    >
      <el-form
        ref="systemFormRef"
        :model="systemForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="系统名称" prop="name">
          <el-input v-model="systemForm.name" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="系统类型" prop="type">
          <el-select v-model="systemForm.type" placeholder="请选择系统类型">
            <el-option
              v-for="item in systemTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接口地址" prop="apiUrl">
          <el-input v-model="systemForm.apiUrl" placeholder="请输入接口地址" />
        </el-form-item>
        <el-form-item label="认证方式" prop="authType">
          <el-select v-model="systemForm.authType" placeholder="请选择认证方式">
            <el-option
              v-for="item in authTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="认证信息" prop="authConfig">
          <el-input
            v-model="systemForm.authConfig"
            type="textarea"
            :rows="3"
            placeholder="请输入认证信息（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="数据映射" prop="dataMapping">
          <el-input
            v-model="systemForm.dataMapping"
            type="textarea"
            :rows="3"
            placeholder="请输入数据映射配置（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="同步配置" prop="syncConfig">
          <el-input
            v-model="systemForm.syncConfig"
            type="textarea"
            :rows="3"
            placeholder="请输入同步配置（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="系统描述" prop="description">
          <el-input
            v-model="systemForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入系统描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 系统监控对话框 -->
    <el-dialog
      v-model="monitorDialogVisible"
      title="系统监控"
      width="1000px"
      append-to-body
    >
      <el-tabs v-model="activeMonitorTab">
        <el-tab-pane label="系统状态" name="status">
          <div class="monitor-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>系统健康度</span>
                    </div>
                  </template>
                  <div class="health-score">
                    <el-progress
                      type="dashboard"
                      :percentage="monitorData.healthScore"
                      :color="getHealthColor"
                    />
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>接口可用性</span>
                    </div>
                  </template>
                  <div class="availability">
                    <el-progress
                      type="dashboard"
                      :percentage="monitorData.availability"
                      :color="getAvailabilityColor"
                    />
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>响应时间</span>
                    </div>
                  </template>
                  <div class="response-time">
                    <h3>{{ monitorData.responseTime }}ms</h3>
                    <p>平均响应时间</p>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="调用趋势" name="trend">
          <div class="monitor-content">
            <div class="chart-container">
              <div ref="trendChartRef" style="width: 100%; height: 400px"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="错误分析" name="error">
          <div class="monitor-content">
            <el-table :data="monitorData.errorList" border style="width: 100%">
              <el-table-column label="错误时间" prop="time" width="180" />
              <el-table-column label="错误类型" prop="type" width="120" />
              <el-table-column label="错误信息" prop="message" show-overflow-tooltip />
              <el-table-column label="处理状态" prop="status" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'resolved' ? 'success' : 'danger'">
                    {{ row.status === 'resolved' ? '已处理' : '未处理' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Plus,
  Edit,
  Delete,
  Search,
  Refresh,
  Download,
  VideoPlay,
  Monitor
} from '@element-plus/icons-vue'
import {
  getSystemList,
  createSystem,
  updateSystem,
  deleteSystem,
  testSystem,
  syncSystem,
  getSystemMonitorData,
  getSystemTrendData
} from '@/api/message'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  status: undefined,
  name: undefined
})

// 系统类型选项
const systemTypes = [
  { label: 'ERP系统', value: 'erp' },
  { label: 'CRM系统', value: 'crm' },
  { label: 'OA系统', value: 'oa' },
  { label: '其他系统', value: 'other' }
]

// 系统状态选项
const systemStatus = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

// 认证方式选项
const authTypes = [
  { label: 'Token认证', value: 'token' },
  { label: 'Basic认证', value: 'basic' },
  { label: 'OAuth2认证', value: 'oauth2' },
  { label: 'API Key', value: 'apikey' }
]

// 数据列表
const loading = ref(false)
const systemList = ref([])
const total = ref(0)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const systemFormRef = ref()
const systemForm = reactive({
  id: undefined,
  name: '',
  type: '',
  apiUrl: '',
  authType: '',
  authConfig: '',
  dataMapping: '',
  syncConfig: '',
  description: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择系统类型', trigger: 'change' }
  ],
  apiUrl: [
    { required: true, message: '请输入接口地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
  ],
  authType: [
    { required: true, message: '请选择认证方式', trigger: 'change' }
  ],
  authConfig: [
    { required: true, message: '请输入认证信息', trigger: 'blur' }
  ]
}

// 监控对话框控制
const monitorDialogVisible = ref(false)
const activeMonitorTab = ref('status')
const monitorData = reactive({
  healthScore: 0,
  availability: 0,
  responseTime: 0,
  errorList: []
})
const trendChartRef = ref(null)
let trendChart = null

// 初始化
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getSystemList(queryParams)
    systemList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('加载系统列表失败:', error)
    ElMessage.error('加载系统列表失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  loadData()
}

// 重置操作
const handleReset = () => {
  queryParams.type = undefined
  queryParams.status = undefined
  queryParams.name = undefined
  handleQuery()
}

// 新增系统
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(systemForm, {
    id: undefined,
    name: '',
    type: '',
    apiUrl: '',
    authType: '',
    authConfig: '',
    dataMapping: '',
    syncConfig: '',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑系统
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(systemForm, row)
  dialogVisible.value = true
}

// 删除系统
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该系统吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteSystem(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除系统失败:', error)
      ElMessage.error('删除系统失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!systemFormRef.value) return
  await systemFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await createSystem(systemForm)
          ElMessage.success('新增成功')
        } else {
          await updateSystem(systemForm)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('保存系统失败:', error)
        ElMessage.error('保存系统失败')
      }
    }
  })
}

// 测试系统
const handleTest = async (row) => {
  try {
    const res = await testSystem(row.id)
    ElMessage.success(res.data.message || '测试成功')
  } catch (error) {
    console.error('测试系统失败:', error)
    ElMessage.error('测试系统失败')
  }
}

// 同步数据
const handleSync = async () => {
  try {
    await syncSystem()
    ElMessage.success('同步成功')
    loadData()
  } catch (error) {
    console.error('同步数据失败:', error)
    ElMessage.error('同步数据失败')
  }
}

// 导出配置
const handleExport = () => {
  // TODO: 实现配置导出功能
  ElMessage.info('配置导出功能开发中')
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await updateSystem({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 监控系统
const handleMonitor = async (row) => {
  monitorDialogVisible.value = true
  activeMonitorTab.value = 'status'
  
  try {
    // 加载监控数据
    const [monitorRes, trendRes] = await Promise.all([
      getSystemMonitorData({ id: row.id }),
      getSystemTrendData({ id: row.id })
    ])
    
    Object.assign(monitorData, monitorRes.data)
    
    // 初始化趋势图表
    if (trendChartRef.value) {
      if (!trendChart) {
        trendChart = echarts.init(trendChartRef.value)
      }
      trendChart.setOption({
        title: {
          text: '系统调用趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: trendRes.data.times
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '调用次数',
            type: 'line',
            data: trendRes.data.counts
          },
          {
            name: '响应时间',
            type: 'line',
            yAxisIndex: 1,
            data: trendRes.data.responseTimes
          }
        ]
      })
    }
  } catch (error) {
    console.error('加载监控数据失败:', error)
    ElMessage.error('加载监控数据失败')
  }
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  loadData()
}

// 计算属性
const getHealthColor = computed(() => {
  const score = monitorData.healthScore
  if (score >= 90) return '#67C23A'
  if (score >= 70) return '#E6A23C'
  return '#F56C6C'
})

const getAvailabilityColor = computed(() => {
  const score = monitorData.availability
  if (score >= 99.9) return '#67C23A'
  if (score >= 99) return '#E6A23C'
  return '#F56C6C'
})

// 工具方法
const getSystemTypeLabel = (type) => {
  const found = systemTypes.find(item => item.value === type)
  return found ? found.label : type
}

const getSystemTypeTag = (type) => {
  const typeMap = {
    erp: '',
    crm: 'success',
    oa: 'warning',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

const getAuthTypeLabel = (type) => {
  const found = authTypes.find(item => item.value === type)
  return found ? found.label : type
}

const getSyncStatusLabel = (status) => {
  const statusMap = {
    success: '同步成功',
    failed: '同步失败',
    syncing: '同步中',
    pending: '待同步'
  }
  return statusMap[status] || status
}

const getSyncStatusTag = (status) => {
  const statusMap = {
    success: 'success',
    failed: 'danger',
    syncing: 'warning',
    pending: 'info'
  }
  return statusMap[status] || 'info'
}
</script>

<style lang="scss" scoped>
.monitor-integration {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .left {
      display: flex;
      align-items: center;
      gap: 10px;

      h2 {
        margin: 0;
        font-size: 20px;
      }
    }

    .right {
      display: flex;
      gap: 10px;
    }
  }

  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }

  .monitor-content {
    padding: 20px;

    .health-score,
    .availability,
    .response-time {
      text-align: center;
      padding: 20px 0;

      h3 {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }

      p {
        margin: 10px 0 0;
        color: #909399;
      }
    }

    .chart-container {
      margin-top: 20px;
    }
  }
}

.ml-2 {
  margin-left: 8px;
}
</style> 